package com.atguigu.flink0624.chapter07;

import com.atguigu.flink0624.bean.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/13 9:27
 */
public class Flink08_Window_Aggregate {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            })
            .keyBy(WaterSensor::getId)
            .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
            .aggregate(
                new AggregateFunction<WaterSensor, Avg, Double>() {
                    // 创建一个累加器: 初始化累加器
                    //每个窗口执行一次
                    @Override
                    public Avg createAccumulator() {
                        System.out.println("Flink08_Window_Aggregate.createAccumulator");
                        return new Avg();
                    }
                    
                    // 累加
                    // 每来一个元素执行一次
                    @Override
                    public Avg add(WaterSensor value, Avg acc) {
                        System.out.println("Flink08_Window_Aggregate.add");
                        acc.sum += value.getVc();
                        acc.count++;
                        return acc;
                    }
                    
                    // 返回终止结果
                    // 窗口关闭的时候, 执行一次
                    @Override
                    public Double getResult(Avg acc) {
                        System.out.println("Flink08_Window_Aggregate.getResult");
                        return acc.avg();
                    }
                    
                    // 两个累计爱进行合并: 只有在session'窗口中才会使用, 其他的窗口可以不用实现
                    @Override
                    public Avg merge(Avg a, Avg b) {
                        System.out.println("Flink08_Window_Aggregate.merge");
                        return null;
                    }
                },
                new WindowFunction<Double, String, String, TimeWindow>() {
                    @Override
                    public void apply(String key,
                                      TimeWindow window,
                                      Iterable<Double> input,
                                      Collector<String> out) throws Exception {
                        Double result = input.iterator().next();
                        out.collect(key + "  " + window + "   " + result);
                    }
                }
            )
            .print();
        
        env.execute();
    }
    
    public static class Avg {
        public Integer sum = 0;
        public Long count = 0L;
        
        public Double avg() {
            return sum * 1.0 / count;
        }
    }
}
/*
sum max min maxBy minBy 都属于增量聚合

reduce
     增量聚合
 */